<!-- 实体标签和关系标签 -->
<template>
  <div class="label-card">
    <div class="title-bar-wrap">
      <div v-show="showSearchInput" class="search-input-wrap">
        <a-input
          v-model:value="searchValue"
          v-trim
          placeholder="请输入标签"
          allow-clear
          type="text"
          @blur="onInputBlur"
          @press-enter="handleSearch"
        >
          <template #prefix>
            <i class="iconfont icon-search-line"></i>
          </template>
        </a-input>
      </div>
      <title-bar v-show="!showSearchInput" title="标签">
        <template #left v-if="type === 'textTriplet'">
          <switch-tabs class="switch-tabs" :selected-tab="selectedTab" :tabs="tabs" @switch-tab="changeTab" />
        </template>
        <template #right>
          <div class="flex gap-x-20">
            <a-button type="text" class="icon-only-btn" @click="handleOpenSearch">
              <i class="iconfont icon-search-line"></i>
            </a-button>
            <a-button v-if="isEditable" type="text" class="icon-only-btn" @click="handleCreate">
              <i class="iconfont icon-add-line"></i>
            </a-button>
          </div>
        </template>
      </title-bar>
    </div>
    <div class="sub-title-bar">
      <div>名称</div>
      <div v-if="type === 'entity' || selectedTab === 'entity'">快捷键</div>
    </div>
    <div class="label-card-content my-scrollbar">
      <entity-label
        v-if="type === 'entity' || selectedTab === 'entity'"
        ref="entityLabelRef"
        :task-info="taskInfo"
        :type="type"
        :search-value="searchValue"
        @shortcut-key-trigger="shortcutKeyTrigger"
        @delete="handleEntityDelete"
        @update="handleEntityUpdate"
        @click-label="shortcutKeyTrigger"
      />
      <relation-label v-else ref="relationLabelRef" :task-info="taskInfo" :search-value="searchValue" @delete="handleRelationDelete" />
    </div>
  </div>

  <entity-label-form ref="entityLabelFormRef" :title="labelFormTitle" show-continue @on-submit="onEntityLabelFormSubmit" />
  <relation-label-form ref="relationLabelFormRef" :title="labelFormTitle" show-continue @on-submit="onRelationLabelFormSubmit" />
</template>

<script setup lang="ts">
  import { message } from 'ant-design-vue'
  import { inject, nextTick, Ref, ref } from 'vue'

  import { textLabelTagApi } from '@/services/index'

  import EntityLabelForm from '../EntityLabelForm.vue'
  import RelationLabelForm from '../RelationLabelForm.vue'
  import TitleBar from '../TitleBar.vue'
  import EntityLabel from './EntityLabel.vue'
  import RelationLabel from './RelationLabel.vue'

  export interface LabelCardProps {
    taskInfo: any
    // 类型 entity: 实体标签, textTriplet: 文本三元组
    type?: 'entity' | 'textTriplet'
  }
  const props = withDefaults(defineProps<LabelCardProps>(), {
    type: 'textTriplet'
  })

  const emits = defineEmits<{
    (event: 'shortcutKeyTrigger', data: any): void
    (event: 'entityDelete', data: any): void
    (event: 'relationDelete', data: any): void
    (event: 'entityUpdate', data: any): void
  }>()

  // 是否可编辑
  const isEditable = inject<Ref<boolean>>('isEditable') || ref(true)

  const entityLabelRef = ref<InstanceType<typeof EntityLabel>>()
  const relationLabelRef = ref<InstanceType<typeof RelationLabel>>()
  const entityLabelFormRef = ref<InstanceType<typeof EntityLabelForm>>()
  const relationLabelFormRef = ref<InstanceType<typeof RelationLabelForm>>()

  const labelFormTitle = ref('创建标签')

  const shortcutKeyTrigger = (data: any) => {
    emits('shortcutKeyTrigger', data)
  }
  const handleEntityDelete = (data: any) => {
    isEditable?.value && emits('entityDelete', data)
  }
  const handleEntityUpdate = (data: any) => {
    isEditable?.value && emits('entityUpdate', data)
  }
  const handleRelationDelete = (data: any) => {
    isEditable?.value && emits('relationDelete', data)
  }

  // ------------------------------------------------ Tab切换 -------------------------------------------------
  const tabs = [
    { name: '实体标签', key: 'entity' },
    { name: '关系标签', key: 'relation' }
  ]
  const selectedTab = ref(tabs[0].key)
  const changeTab = async (key: string) => {
    selectedTab.value = key
    searchValue.value = ''
    await nextTick()
    const scrollBar = document.querySelector('.label-card-content')
    if (selectedTab.value === 'entity') {
      entityLabelRef.value?.getLabelList({ taskId: props?.taskInfo?.id })
    } else {
      relationLabelRef.value?.getLabelList({ taskId: props?.taskInfo?.id })
    }
    if (scrollBar) {
      scrollBar.scrollTop = 0
    }
  }

  // ------------------------------------------------ 创建标签 -------------------------------------------------
  const handleCreate = () => {
    if (props.type === 'entity' || selectedTab.value === 'entity') {
      labelFormTitle.value = props.type === 'entity' ? '创建标签' : '创建实体标签'
      entityLabelFormRef.value?.open()
    } else {
      labelFormTitle.value = '创建关系标签'
      relationLabelFormRef.value?.open({ taskId: props?.taskInfo?.id })
    }
  }
  // 实体标签表单提交
  const onEntityLabelFormSubmit = async (formState: any, isContinue: boolean) => {
    try {
      await textLabelTagApi.add(
        {
          taskId: props.taskInfo?.id,
          name: formState.name,
          color: formState.color
        },
        {
          isAddUid: true
        }
      )

      message.success('标签创建成功')
      entityLabelRef.value?.getLabelList()
      if (isContinue) {
        // 继续创建
        entityLabelFormRef.value?.resetForm()
        return
      }
      entityLabelFormRef.value?.close()
    } catch (error: any) {
    } finally {
      entityLabelFormRef.value?.hideLoading()
    }
  }
  // 关系标签表单提交
  const onRelationLabelFormSubmit = async (formState: any, isContinue: boolean) => {
    try {
      await textLabelTagApi.addRelation(
        {
          taskId: props.taskInfo?.id,
          name: formState.name,
          beginLabelId: formState.startLabel,
          endLabelId: formState.endLabel,
          type: 3
        },
        {
          isAddUid: true
        }
      )

      message.success('标签创建成功')
      relationLabelRef.value?.getLabelList()
      if (isContinue) {
        // 继续创建
        relationLabelFormRef.value?.resetForm()
        return
      }
      relationLabelFormRef.value?.close()
    } catch (error: any) {
    } finally {
      relationLabelFormRef.value?.hideLoading()
    }
  }

  // ----------------------------------------------- 搜索 ------------------------------------------------
  const searchValue = ref('')
  const showSearchInput = ref(false)
  const handleOpenSearch = async () => {
    showSearchInput.value = true
    await nextTick()
    const input = document.querySelector('.search-input-wrap input') as any
    if (input) {
      input.focus()
    }
  }
  const onInputBlur = () => {
    showSearchInput.value = false
  }
  const handleSearch = () => {
    if (props.type === 'entity' || selectedTab.value === 'entity') {
      entityLabelRef.value?.search(searchValue.value)
    } else {
      relationLabelRef.value?.search(searchValue.value)
    }
  }
</script>

<style lang="less" scoped>
  .label-card {
    display: flex;
    width: 100%;
    height: 100%;
    min-height: 0;
    flex-direction: column;

    .title-bar-wrap {
      flex-shrink: 0;
      height: 46px;

      .switch-tabs {
        :deep(.tabs) {
          .tab {
            padding: 0 10px;

            & + .tab {
              margin-left: 8px;
            }
          }
        }
      }

      .search-input-wrap {
        padding: 4px 24px;
      }
    }

    .sub-title-bar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 24px;
      height: 40px;
      font-size: 14px;
      color: @text03;
      font-weight: 700;
      line-height: 22px;
      border-bottom: 1px solid @border1;
    }

    .label-card-content {
      overflow-y: auto;
      width: 100%;
      flex: 1;
    }
  }
</style>
